﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using NetFtp.Core.Login;

namespace NetFtp.Core.DAO
{
    public class FtpAccountAccess
    {
        private DataSetTableAdapters.ftpAccountTableAdapter connexionAccount;
        private DataSet cacheAccount;
        private IList<FtpAccount> ftpAccounts;

        private DataSetTableAdapters.UserTableAdapter connexionUser;
        private DataSet cacheUser;

        public FtpAccountAccess()
        {
            cacheUser = new DataSet();
            connexionUser = new DataSetTableAdapters.UserTableAdapter();
            connexionUser.Fill(cacheUser.User);

            cacheAccount = new DataSet();
            connexionAccount = new DataSetTableAdapters.ftpAccountTableAdapter();
            ftpAccounts = new List<FtpAccount>();
        }

        public void Fill(User user)
        {
            connexionAccount.Fill(cacheAccount.ftpAccount, user.Id);

            ftpAccounts.Clear();
            foreach (DataSet.ftpAccountRow row in cacheAccount.ftpAccount.Rows)
            {
                this.ftpAccounts.Add(new FtpAccount(row.ftpId, row.hostname, row.username, row.password, row.port, row.folder));
            }
        }

        public IList<FtpAccount> FtpAccounts
        {
            get
            {
                return this.ftpAccounts;
            }
        }

        /// <summary>
        /// Sauve an bdd le compte FTP.
        /// </summary>
        /// <param name="ftpAccount"></param>
        public void DoSave(FtpAccount ftpAccount, User user)
        {
            DataSet.UserRow tmpuser = null;

            foreach (DataSet.UserRow row in cacheUser.User.Rows)
            {
                if (row.username == user.Username)
                    tmpuser = row;
            }

            cacheAccount.ftpAccount.AddftpAccountRow(tmpuser, ftpAccount.Hostname, ftpAccount.Port, ftpAccount.Folder, ftpAccount.Username, ftpAccount.Password);
            connexionAccount.Update(cacheAccount);
            connexionAccount.Fill(cacheAccount.ftpAccount, user.Id);

            ftpAccounts.Clear();
            foreach (DataSet.ftpAccountRow row in cacheAccount.ftpAccount.Rows)
            {
                this.ftpAccounts.Add(new FtpAccount(row.ftpId, row.hostname, row.username, row.password, row.port, row.folder));
            }
        }

        /// <summary>
        /// Hydrate le compte FTP existant.
        /// </summary>
        /// <param name="ftpAccount"></param>
        public void DoUpdate(FtpAccount ftpAccount)
        {
        }

        /// <summary>
        /// Supprime le compte FTP existant.
        /// </summary>
        /// <param name="ftpAccount"></param>
        public void DoRemove(FtpAccount ftpAccount)
        {
            connexionAccount.Delete(ftpAccount.Id);
        }
    }
}
